package net.zjitc.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2017/9/28.
 */
@WebServlet(name = "CookieServlet",urlPatterns = "/cookieServlet")
public class CookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        /*Cookie cookie=new Cookie("name","zhangsan");
        response.addCookie(cookie);
        response.getWriter().write("我已经有cookie了...");*/



        Cookie[] cookies=request.getCookies();
        String lastTime=null;
        PrintWriter out=response.getWriter();
        //这个for是找出你是否是第一次访问，如果是第一次访问就不执行这个for循环，如果不是第一次访问就执行并记录下访问时间
        for (int i = 0; cookies != null && i <cookies.length ; i++) {
            String name=cookies[i].getName();
            if("lastAccessTime".equals(name)) {//key
                lastTime = cookies[i].getValue();//value
                break;
            }
        }
        //判断上次访问是否为空
        if(lastTime==null){
            out.write("你是第一次访问");
        }else{
            out.write("上一次访问时间"+lastTime);
        }
        //把当前对时间，要带给浏览器， key - value(String)
        //时间---->字符串
        String currenTime=new SimpleDateFormat("yyyy-MM-dd#HH:mm:ss").format(new Date());
        Cookie cookie = new Cookie("lastAccessTime",currenTime);
        response.addCookie(cookie);
    }
}
